console.log('tax injected');
import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';
import { syncReportInfoHelper } from './help.js';
import { startZeroReport,checkZeroReport } from './zeroReport.js';


// import { dealReports } from '../commonModule/J.js';


let baseInfo;

window.onload = function () {

  window.postMessage(
    {
      event: 'getZeroInfo'
    },
    '*'
  );
  checkZeroReport();

  let pathName = window.location.pathname;
  // 登录填写账号密码
  if (/\/dzswjlogin\/dzswj_login/g.test(pathName) || /\/EnterpriseWsswjLoginAction.do/g.test(pathName)) {
    if (document.getElementById('userId')) {
      window.postMessage({
        event: 'getBaseInfo'
      }, '*');
    }
  }

  // 同步申报表
  if (/EnterpriseDzswjMainAction\.do/g.test(window.location.href)) {
    syncReportInfoHelper.captureDataFromPage();
  }
  if (/\/EnterpriseWsswjLoginAction.do/g.test(pathName)) {
    // 获取左侧导航栏和右侧表单frame对象
    let frmLeft = document.querySelectorAll('frame')[1];
    let frmRight = document.querySelectorAll('frame')[2];
    // hack原网页的方法和对象：AddTab
    frmLeft.contentWindow.AddTab = function (url) {
      frmRight.contentWindow.location = url;
    };

    frmRight.onload = function () {
      let frmRightURL = frmRight.contentWindow.location.href;
      // 强制增值税弹出保存成功的页面
      if (frmRightURL.indexOf('ReportYGZ_ZzsXGM_2016_Action.do?activity=saveData&reportname=YGZ_SB_ZZS_XGMNSR_JD') > -1) {
        alert('保存成功！');
      }
      // 新建一个全局的input对象来作为编辑框
      frmRight.contentWindow.cellInputDom = frmRight.contentWindow.document.createElement('input');
      frmRight.contentWindow.cellInputDom.currentCell = null;
      // 双击表格时出现编辑框
      frmRight.contentWindow.document.querySelector('#tab').ondblclick = (event) => {
        if (event.target.getAttribute('id') && !event.target.getAttribute('acf')) {
          frmRight.contentWindow.cellInputDom.value = parseFloat(event.target.innerText.replace(/\s+/g, ''));
          frmRight.contentWindow.cellInputDom.currentCell = event.target;
          event.target.appendChild(frmRight.contentWindow.cellInputDom);
        }
      };
      // 编辑框失去焦点的时候，给对应表格元素赋值，并触发自动计算
      frmRight.contentWindow.cellInputDom.onblur = function () {
        if (/^-?\d+\.?\d*$/.test(this.value)) {
          this.currentCell.innerText = parseFloat(this.value);
          if (this.currentCell.getAttribute('acp')) {
            frmRight.contentWindow.doAutoCalculation(this.currentCell);
          }
        }
      };

      frmRight.contentWindow.cellInputDom.onkeyup = function () {
        if (!/^-?\d+\.?\d*$/.test(this.value)) {
          alert('请不要输入非数字');
        }
      };

      // 查询报税周期
      let dateAndTypeObj = findDateAndType(frmRight.contentWindow.document);
      console.log(dateAndTypeObj);
      // 给过滤框添加数据
      if (dateAndTypeObj.period && dateAndTypeObj.type) {
        let period = dateAndTypeObj.period;
        period = period.split('-');
        window.postMessage({
          event: 'setPeriodAndType',
          data: {
            type: dateAndTypeObj.type,
            startTime: period[0].replace(/(\d{4})/g, '$1-'),
            endTime: period[1].replace(/(\d{4})/g, '$1-')
          }
        }, '*');
      }
      // hack原网页的方法和对象：tags
      frmRight.contentWindow.document.all.tags = function (td) {
        return frmRight.contentWindow.document.querySelectorAll(td);
      };
      // hack原网页的方法和对象：workTab
      frmRight.contentWindow.workTab = frmRight.contentWindow.document.querySelector('#tab');
    };
    // 给frame里面的页面增加滚动条
    document.querySelectorAll('frame').forEach(function (frame) {
      frame.setAttribute('scrolling', 'auto');
    });
  }
};


window.addEventListener('message', async function ({ data }) {
  // 只监听来自于content script的信息
  if (data.sender !== 'content-script') {
    return false;
  }
  if (data.event === 'setSaasData') {
    fillInput(await transformDataByOpenWeb(data.data));
  }
  if (data.event === 'getNationData') {
    getNationData();
  }
  if (data.event === 'getBaseInfo') {
    baseInfo = data.data;
    autoInputAccount(baseInfo);
  }
  // 同步申报表种类
  if (data.event === 'syncReportInfo') {
    syncReportInfoHelper.startGetReportInfo();
  }
  // 同步申报表
  if (data.event === 'syncReport') {
    syncReportInfoHelper.startGetReport();
  }
  if (data.event === 'getZeroInfoBack') {
    if(data.data.isOpenZeroReport){
      let backInfo = await startZeroReport(data);
    }
  }
}, false);

/**
 * 获取公司信息
 */
function getNationData() {
  let taxInfo = {
    institution: getGsInstitution() === 'small' ? '2013' : '2007', // 国税对应制度 2007 | 2013
    nsrsbh: '', // 纳税人申报号
    nsrmc: '', // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: ''// 税款所属期止
  };
  window.postMessage({
    event: 'backNationData',
    data: {
      taxInfo: taxInfo
    }
  }, '*');
}


function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  console.log(companyInfo);
  $('#userId').val(companyInfo.nationalTaxId).trigger('blur');
  $('#czydm').val(companyInfo.nationalTaxAccount).trigger('blur');
  $('#password').val(companyInfo.nationalTaxPass).trigger('blur');

  // $('#userId').val('91370102MA3CC2QR0Q').trigger('blur');
  // $('#password').val('jnlq6666').trigger('blur');
}

function fillInput({ saasData }) {
  let frmRight = document.querySelector('#FRM_RIGHT');

  // 给dom元素写入ACF和ACP的属性
  frmRight.contentWindow.document.querySelectorAll('*').forEach((DOM) => {
    if (DOM.getAttribute('acf')) {
      DOM.ACF = DOM.getAttribute('acf');
    }
    if (DOM.getAttribute('acp')) {
      DOM.ACP = DOM.getAttribute('acp');
    }
  });

  let inputData = saasData.data;
  let message = '填报成功';
  try {
    // 将传入的数据写入DOM中
    for (let key in inputData) {
      let frmDOM = frmRight.contentWindow.document.querySelector(`#${key}`);
      frmDOM.innerText = Number(inputData[key]).toFixed(2);
    }

    // 在所有原始数据都被写入之后，触发自动计算
    frmRight.contentWindow.document.querySelectorAll('[acp]').forEach((DOM) => {
      if (!DOM.getAttribute('acf')) {
        frmRight.contentWindow.doAutoCalculation(DOM);
      }
    });
  } catch (e) {
    message = '填报失败';
  }

  // todo finally
  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message
    }
  }, '*');
}

function getGsInstitution() {
  return 'small';
}

function findDateAndType(document) {
  // 尝试获取申报周期
  let reportingDate = '';
  let found = false;
  document.querySelectorAll('.noborder').forEach(function (noborderEle) {
    let yearIndex = [];
    let monthIndex = [];
    let yearStr1 = '';
    let monthStr1 = '';
    let yearStr2 = '';
    let monthStr2 = '';
    if ((noborderEle.innerText.indexOf('年') !== -1) && (noborderEle.innerText.indexOf('月') !== -1) && !found) {
      found = true;
      for (let i = 0; i < noborderEle.innerText.length; i++) {
        if (noborderEle.innerText[i] === '年') {
          yearIndex.push(i);
        } else if (noborderEle.innerText[i] === '月') {
          monthIndex.push(i);
        }
      }
      yearStr1 = noborderEle.innerText.substring(yearIndex[0] - 4, yearIndex[0]).replace(/\s+/g, '');
      monthStr1 = noborderEle.innerText.substring(yearIndex[0] + 1, monthIndex[0]).replace(/\s+/g, '');

      // 如果是跨季度的话
      if (yearIndex[1] && monthIndex[1]) {
        yearStr2 = noborderEle.innerText.substring(yearIndex[1] - 4, yearIndex[1]).replace(/\s+/g, '');
        monthStr2 = noborderEle.innerText.substring(yearIndex[1] + 1, monthIndex[1]).replace(/\s+/g, '');
        monthStr1 = monthStr1.length === 1 ? '0' + monthStr1 : monthStr1;
        monthStr2 = monthStr2.length === 1 ? '0' + monthStr2 : monthStr2;
        reportingDate = yearStr1 + monthStr1 + '-' + yearStr2 + monthStr2;
        // 如果不跨季度
      } else {
        monthStr2 = monthStr1;
        monthStr1 = monthStr1.length === 1 ? '0' + monthStr1 : monthStr1;
        monthStr2 = monthStr2.length === 1 ? '0' + monthStr2 : monthStr2;
        reportingDate = yearStr1 + monthStr2 + '-' + yearStr1 + monthStr1;
      }
    }
  });
  // 尝试获取税表类型
  let reportingType = '';
  let tableTitle = document.querySelector("[align='center'].title") || document.querySelector("[align='middle'].title");
  if (tableTitle && tableTitle.innerText.replace(/\s+/g, '').indexOf('利润表') > -1) {
    reportingType = 'profit';
  } else if (tableTitle && tableTitle.innerText.replace(/\s+/g, '').indexOf('资产负债表') > -1) {
    reportingType = 'balance';
  } else if (tableTitle && tableTitle.innerText.replace(/\s+/g, '').indexOf('所得税') > -1) {
    reportingType = 'sds';
  } else if (tableTitle && tableTitle.innerText.replace(/\s+/g, '').indexOf('增值税') > -1) {
    reportingType = 'zzs';
  } else if (tableTitle && tableTitle.innerText.replace(/\s+/g, '').indexOf('现金流量表') > -1) {
    reportingType = 'cash';
  }
  return {
    period: reportingDate,
    type: reportingType
  };
}
